import React, { Fragment, PropsWithChildren } from "react";
import { useSearchParams } from "react-router-dom";
import type { RouteConfig } from "@/pro-router/types";

import { loadable } from "@yaf/react-loadable";

interface BusinessComponentProps {
  DynamicComponent: React.FC<PropsWithChildren<{ urlParams: any }>>;
  ThemeConfigProvider?: React.FC<PropsWithChildren>
}

const BusinessComponent: React.FC<PropsWithChildren<BusinessComponentProps>> = ({ DynamicComponent, ThemeConfigProvider = Fragment, children, ...restProps }) => {
  const [urlSearchParams] = useSearchParams();
  const urlParams: { [index: string]: any } = {};
  // @ts-ignore
  const values = urlSearchParams.entries();
  for (let [key, value] of values) {
    urlParams[key] = value;
  }

  return (
    <ThemeConfigProvider>
      <DynamicComponent
        urlParams={values}
        {...restProps}
      >
        {children}
      </DynamicComponent>
    </ThemeConfigProvider>
  )
}

export const withBusinessComponent = (item: RouteConfig, ThemeConfigProvider?: React.FC<PropsWithChildren>) => {
  const { component, isLayout = false } = item;
  const DynamicComponent = component ? (component instanceof Promise ? loadable(component, {loadingStyle: {height: "100%"}}) : component) : ({ children }: any) => children;
  const RealBusinessComponent = isLayout ? DynamicComponent : (props: any) => <BusinessComponent DynamicComponent={DynamicComponent} ThemeConfigProvider={ThemeConfigProvider} {...props} />;

  return RealBusinessComponent;
}
